﻿using codeGen.Model;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using RazorEngine;
using RazorEngine.Templating;
namespace codeGen
{
    public class GenrateService : IHostedService
    {
        private readonly IConfiguration _configuration;
        private readonly IHostApplicationLifetime _hostApplicationLifetime;

        private readonly List<TaskConfig> _options;
        public GenrateService(IConfiguration configuration, IHostApplicationLifetime hostApplicationLifetime, IOptions<List<TaskConfig>> options)
        {
            _configuration = configuration;
            _hostApplicationLifetime = hostApplicationLifetime;
            _options = options.Value;
        }
        public Task StartAsync(CancellationToken cancellationToken)
        {
            Genrate();
            _hostApplicationLifetime.StopApplication();
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        private void Genrate()
        {
            foreach (var item in _options)
            {
                Directory.CreateDirectory(item.InputDir);
                Directory.CreateDirectory(item.OutputDir);
                string template = File.ReadAllText(item.TemplatePath);
                try
                {
                    foreach (var file in Directory.GetFiles(item.InputDir))
                    {
                        var data = handlerSource(file);
                        var result = Engine.Razor.RunCompile(template, Guid.NewGuid().ToString(), model: data);
                        File.WriteAllText(Path.Combine(item.OutputDir,string.Format(item.FileNameFormat, data.ClassName)), result);
                        Console.WriteLine($"{item.TemplatePath} 生成完成");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{item.TemplatePath} 生成代码发生错误");
                }
            }
        }
        private ClassMetadata handlerSource(string sourcePath)
        {
            var currentRow = 0;
            ClassMetadata data = new ClassMetadata();
            using (FileStream fs = new FileStream(sourcePath,FileMode.Open))
            { 
                using (StreamReader sr = new StreamReader(fs))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        if(currentRow == 0)
                        {
                            string[] lineValue = line.Split(',');
                            data.ClassName = lineValue[0];
                            data.ClassComment = lineValue[1];

                            currentRow++;
                            continue;
                        }
                        string[] fieldInfos = line.Split(',');
                        data.Fields.Add(new FieldMetadata 
                        {
                            FieldName = fieldInfos[0],
                            FieldComment = fieldInfos[1],
                            FieldType = fieldInfos[2], 
                        });
                        currentRow++;
                    }
                }
            }
            return data;
        }
    }
}
